import Router from 'koa-router'
import axios from 'axios'
import StudentModel from '../dbs/models/student'
import dormInfoModel from '../dbs/models/dormInfo'

let router = new Router({ prefix: '/student' })

// 所有学生列表接口
router.get('/studentList', async (ctx, next) => {
  let page = Number(ctx.query.pagenum)//当前第几页
  let size = Number(ctx.query.pagesize)//每页显示的记录条数
  let options = { "limit": size, "skip": (page - 1) * size }
  let result = await StudentModel.find({}, null, options).sort({ "tower": 1, "dorm": 1 })
  let count = await StudentModel.find({}, null)
  let total = count.length
  ctx.body = {
    total: total,
    studentlist: result,
    meta: {
      msg: "请求数据成功",
      code: 200
    }
  }
})
// 搜索学生接口
router.get('/findStudent', async (ctx, next) => {
  let query = ctx.query.query
  let tower = ctx.query.tower
  // console.log('kankan：', ctx.query)
  // console.log('查找学生：', query)
  /**
   * let nameReg = new RegExp("[\\u4E00-\\u9FFF]+")
   * 后面加g，进行全局匹配
   * 发现RegExp对象有一个lastIndex的属性，如果使用了全局修饰符，那么执行test方法后
   * lastIndex就会记录匹配的字符串在原始字 符串中最后一位的索引加一，
   * 例如执行了var result1 = re.test(str)后lastIndex为3(document.write('re.lastindex:' + re.lastIndex+ '<br/>');)，
   * 如果没有发现匹配lastIndex置为0。当下次再执行时，
   * 对给定的字符串匹配不是从开头位置，而是要依据lastIndex提供的位置，由于这个原因，所以导致上例中result2的值为false。
   * 
   * 所以使用了console.log('文字', nameReg.test(query))来查看值以后，
   * 就会导致后面的if判断是false
   * 解决办法就是不要使用全局修饰符g
   */
  if (!tower) {
    let nameReg = new RegExp("[\\u4E00-\\u9FFF]+")
    let studentNum = new RegExp("[0-9]")
    let where = {}
    if (nameReg.test(query)) {
      where = {
        name: query
      }
      let result = await StudentModel.find(where, null)
      if (result.length) {
        ctx.body = {
          result,
          meta: {
            msg: "请求数据成功",
            code: 200
          }
        }
      } else {
        ctx.body = {
          result,
          meta: {
            msg: "没有该学生",
            code: 100
          }
        }
      }

    } else if (studentNum.test(query)) {
      where = {
        studentNumber: query
      }
      let result = await StudentModel.find(where, null)
      if (result.length) {
        ctx.body = {
          result,
          meta: {
            msg: "请求数据成功",
            code: 200
          }
        }
      } else {
        ctx.body = {
          result,
          meta: {
            msg: "没有该学生",
            code: 100
          }
        }
      }

    } else {
      // 如果没有搜索内容，就返回最开始的列表样子
      const { data: res } = await axios.get('http://127.0.0.1:3000/student/studentList', {
        params: {
          pagenum: 1,
          pagesize: 7
        }
      })
      if (res.meta.code !== 200) {
        console.log('获取列表失败')
        return
      } else {
        let { studentlist: result } = res
        ctx.body = {
          result,
          meta: {
            msg: '请输入名字或者学号',
            code: 100
          }
        }
      }
    }
  } else {
    let nameReg = new RegExp("[\\u4E00-\\u9FFF]+")
    let studentNum = new RegExp("[0-9]")
    let where = {}
    if (nameReg.test(query)) {
      where = {
        tower,
        name: query
      }
      let result = await StudentModel.find(where, null)
      if (result.length) {
        ctx.body = {
          result,
          meta: {
            msg: "请求数据成功",
            code: 200
          }
        }
      } else {
        ctx.body = {
          result,
          meta: {
            msg: `${where.tower}没有该学生`,
            code: 100
          }
        }
      }

    } else if (studentNum.test(query)) {
      where = {
        tower,
        studentNumber: query
      }
      let result = await StudentModel.find(where, null)
      if (result.length) {
        ctx.body = {
          result,
          meta: {
            msg: "请求数据成功",
            code: 200
          }
        }
      } else {
        ctx.body = {
          result,
          meta: {
            msg: `${where.tower}没有该学生`,
            code: 100
          }
        }
      }

    } else {
      // 如果没有搜索内容，就返回最开始的列表样子
      const { data: res } = await axios.get('http://127.0.0.1:3000/student/studentList', {
        params: {
          pagenum: 1,
          pagesize: 7
        }
      })
      if (res.meta.code !== 200) {
        console.log('获取列表失败')
        return
      } else {
        let { studentlist: result } = res
        ctx.body = {
          result,
          meta: {
            msg: '请输入名字或者学号',
            code: 100
          }
        }
      }
    }
  }

})
// 当前宿舍楼宇所有学生
router.get('/findCurtTowerSL', async (ctx, next) => {
  let tower = ctx.query.tower
  let page = Number(ctx.query.pagenum)//当前第几页
  let size = Number(ctx.query.pagesize)//每页显示的记录条数
  let where = { tower }
  let options = { "limit": size, "skip": (page - 1) * size }
  let result = await StudentModel.find(where, null, options)
  let count = await StudentModel.find(where, null)
  let total = count.length
  ctx.body = {
    total: total,
    studentlist: result,
    meta: {
      msg: "请求数据成功",
      code: 200
    }
  }
})
// 搜索某栋楼某宿舍的一名学生
router.get('/findCurrentTowerStudents', async (ctx, next) => {
  let where = {
    tower: ctx.query.tower,
    dorm: ctx.query.dorm,
    name: ctx.query.name
  }
  await StudentModel.findOne(where, null, (err, res) => {
    if (!res) {
      ctx.body = {
        meta: {
          msg: '对不起，没有该学生',
          code: 0
        }
      }
      return err
    } else {
      ctx.body = {
        res,
        meta: {
          msg: '已找到',
          code: 1
        }
      }
    }
  })

})
// 添加学生接口
router.get('/addStudent', async (ctx, next) => {
  const addStudent = new StudentModel({
    studentNumber: ctx.query.studentNumber,
    name: ctx.query.name,
    sex: ctx.query.sex,
    college: ctx.query.college,
    class: ctx.query.class,
    tower: ctx.query.tower,
    dorm: ctx.query.dorm,
    tel: ctx.query.tel
  })
  // console.log(addStudent)
  let code
  try {
    await addStudent.save()
    code = 0
  } catch (e) {
    code = -1
  }
  ctx.body = {
    msg: '添加成功',
    code: code
  }
})
// 修改学生信息接口
router.get('/editStudent', async (ctx, next) => {
  let oldStudentInfo = { _id: ctx.query.query }
  let newStudentInfo = {
    name: ctx.query.name,
    sex: ctx.query.sex,
    tower: ctx.query.tower,
    dorm: ctx.query.dorm,
    tel: ctx.query.tel,
    college: ctx.query.college,
    class: ctx.query.class
  }
  await StudentModel.updateOne(oldStudentInfo, newStudentInfo, (err, res) => {
    if (err) {
      ctx.body = {
        msg: '修改失败',
        code: -1
      }
    } else if (res.n === 0) {
      // res是一个对象：如果存在就会返回 {n:1,nmodified: 1,ok:1}
      ctx.body = {
        msg: '修改失败,没有找到该学生',
        code: -1
      }
    } else {
      ctx.body = {
        msg: '修改成功',
        code: 0
      }
    }
  })
})
// 删除学生接口
router.get('/deleteStudent', async (ctx, next) => {
  const deleteStudent = { _id: ctx.query.id }
  // console.log(deleteStudent)
  let code
  try {
    await StudentModel.remove(deleteStudent, null)
    code = 0
  } catch (e) {
    code = -1
  }
  ctx.body = {
    msg: '删除成功',
    code: code
  }
})
// 导入excel的接口
router.get('/addExcelData', async (ctx, next) => {
  // 将json字符串解析回json对象
  var obj = eval('(' + ctx.query.excelList + ')')
  console.log(obj.length)
  let code
  try {
    await StudentModel.insertMany(obj)
    code = 0
  } catch (error) {
    console.log(error)
    code = -1
  }
  ctx.body = {
    msg: code === 0 ? '添加成功' : '添加失败',
    code: code
  }
})
// excel导出接口
router.get('/exportExcel', async (ctx, next) => {
  let query = ctx.query.query
  console.log(query)
  let tower = new RegExp("(桃园|荔园|兰园)[0-9]")
  let college = new RegExp("^[\u4e00-\u9fa5]+$")
  let where = {}
  // console.log(college.test(query))
  // console.log(tower.test(query))
  if (college.test(query)) {
    where = {
      college: query
    }
    let result = await StudentModel.find(where, null)
    if (result.length === 0) {
      ctx.body = {
        msg: '没有该学院',
        code: -1
      }
    } else {
      ctx.body = {
        result: result,
        code: 0
      }
    }


  } else if (tower.test(query)) {
    where = {
      tower: query
    }
    let result = await StudentModel.find(where, null)
    if (result.length === 0) {
      ctx.body = {
        msg: '没有该宿舍楼',
        code: -1
      }
    } else {
      ctx.body = {
        result: result,
        code: 0
      }
    }
  } else {
    where = {
      class: query
    }
    let result = await StudentModel.find(where, null)
    if (result.length === 0) {
      ctx.body = {
        msg: '没有该班级',
        code: -1
      }
    } else {
      ctx.body = {
        result: result,
        code: 0
      }
    }
  }
})
// 上传一寸照接口
router.post('/studentImg', async (ctx, next) => {
  {
    let studentNumber = { studentNumber: ctx.request.body.studentNumber }
    let studentImage = { studentImage: ctx.request.body.studentImage }
    // console.log(studentNumber)
    await StudentModel.updateOne(studentNumber, studentImage, (err, res) => {
      if (err) {
        // console.log(err)
        ctx.body = {
          msg: '上传失败',
          code: -1
        }
      } else if (res.n === 0) {
        // res是一个对象：如果存在就会返回 {n:1,nmodified: 1,ok:1}
        ctx.body = {
          msg: '上传失败,没有找到该学生',
          code: -1
        }
      } else {
        ctx.body = {
          msg: '上传成功',
          code: 0
        }
      }
    })
  }
})
// 学生宿舍
router.get('/myDormInfo', async (ctx, next) => {
  let tower = ctx.query.tower
  let dorm = ctx.query.dorm
  let where = {
    tower,
    dorm
  }
  try {
    let result = await StudentModel.find(where, null)
    if (!result) {
      ctx.body = {
        result,
        meta: {
          msg: "没有该宿舍",
          code: 206
        }
      }
    } else {
      ctx.body = {
        result,
        meta: {
          msg: "请求数据成功",
          code: 200
        }
      }
    }
  } catch (error) {
    throw error
    // console.log(error)
  }
})
// 添加宿舍长
router.get('/addDormLeader', async (ctx) => {
  let where = {
    tower: ctx.query.tower,
    dorm: ctx.query.dorm,
    dormLeader: ctx.query.dormLeader,
    class: ctx.query.class,
    studentNumber: ctx.query.studentNumber
  }
  const addDormLeader = new dormInfoModel(where)
  let code
  try {
    await addDormLeader.save()
    code = 0
  } catch (e) {
    code = -1
  }
  ctx.body = {
    msg: '添加成功',
    code: code
  }
})

// 查看宿舍有没有宿舍长以及床位空缺情况
router.get('/findDormLeader', async (ctx) => {
  let where = {
    tower: ctx.query.tower.split(',')
  }
  // console.log(where)
  let page = Number(ctx.query.pagenum)//当前第几页
  let size = 10
  let options = { "limit": size, "skip": (page - 1) * size }
  // 某栋宿舍楼所有的宿舍长名单
  const result1 = await dormInfoModel.find(where, null, options).sort({ "tower": 1, "dorm": 1 })
  // 某栋宿舍楼的7间宿舍
  const result2 = await StudentModel.find(where, null).sort({ "tower": 1, "dorm": 1 })
  // 某栋宿舍楼的某宿舍所有人  .sort({ "dorm": 1 })
  const result3 = await StudentModel.find(where).sort({ "tower": 1, "dorm": 1 })
  let count = await dormInfoModel.find(where, null)
  let total = count.length
  // 计算宿舍可用床位后的学生某宿舍数组
  let result = []
  if (result2.length !== 0) {
    /** 这个方法有bug，async await，result.push(valid) result数组在这个循环外没有值
    result1.forEach(async valid => {
      let query = {
        tower: valid.tower,
        dorm: valid.dorm
      }
      const result3 = await StudentModel.find(query)
      valid.spare = Number(valid.spare) - result3.length
      result.push(valid)
    })*/
    // 取出整栋宿舍楼每一个宿舍已经入住的人数
    result1.forEach(valid => {
      let query = {
        dorm: valid.dorm
      }
      let need = result3.filter(valid => {
        return valid.dorm === query.dorm
      })
      valid.spare = Number(valid.spare) - need.length
      result.push(valid)
    })
    ctx.body = {
      result,
      total,
      meta: {
        msg: "请求数据成功",
        code: 200
      }
    }
  } else {
    ctx.body = {
      meta: {
        msg: "这栋宿舍楼还没有入住的人呦~",
        code: 204 // 表示已经接受到请求，但是没有内容
      }
    }
  }
})
// 修改宿舍默认容量
router.get('/changeBed', async ctx => {
  let dormId = {
    _id: ctx.query.id
  }
  let newSpare = {
    spare: ctx.query.spare
  }
  // console.log(dormId, newSpare)
  await dormInfoModel.updateOne(dormId, newSpare, (err, res) => {
    if (err) {
      ctx.body = {
        meta: {
          msg: '修改失败',
          code: -1
        }
      }
    } else if (res.n === 0) {
      ctx.body = {
        meta: {
          msg: '修改失败,没有找到该宿舍',
          code: -1
        }
      }
    } else {
      ctx.body = {
        meta: {
          msg: '修改成功',
          code: 0
        }
      }
    }
  })
})
// 修改宿舍长
router.get('/changeDormLeader', async ctx => {
  let where = {
    tower: ctx.query.tower,
    dorm: ctx.query.dorm,
    name: ctx.query.dormLeader
  }
  let query = {
    _id: ctx.query.id
  }

  console.log(where, query)
  // 查找是否存在该学生
  const { data: res } = await axios.get('http://127.0.0.1:3000/student/findCurrentTowerStudents', { params: where })
  // console.log(res)
  if (res.meta.code === 1) {
    let newDormLeader = {
      dormLeader: res.res.name,
      class: res.res.class,
      studentNumber: res.res.studentNumber
    }
    // console.log(newDormLeader)
    await dormInfoModel.updateOne(query, newDormLeader, (err, res) => {
      if (err) {
        ctx.body = {
          meta: {
            msg: '修改失败',
            code: -1
          }
        }
      } else if (res.n === 0) {
        // res是一个对象：如果存在就会返回 {n:1,nmodified: 1,ok:1}
        ctx.body = {
          meta: {
            msg: '修改失败,没有找到该宿舍',
            code: -1
          }
        }
      } else {
        ctx.body = {
          meta: {
            msg: '修改成功',
            code: 1
          }
        }
      }
    })
  } else {
    ctx.body = {
      meta: {
        msg: '对不起，本宿舍没有该学生',
        code: -1
      }
    }
  }

})
// 将最新的宿舍评分添加到dormInfo表中
router.get('/newScore', async ctx => {
  let where = {
    tower: ctx.query.tower,
    dorm: ctx.query.dorm
  }
  let newS = {
    score: ctx.query.score
  }
  await dormInfoModel.updateOne(where, newS, (err, res) => {
    if (err) {
      ctx.body = {
        meta: {
          msg: '修改失败',
          code: -1
        }
      }
    } else if (res.n === 0) {
      ctx.body = {
        meta: {
          msg: '修改失败,没有找到该宿舍',
          code: -1
        }
      }
    } else {
      ctx.body = {
        meta: {
          msg: '修改成功',
          code: 0
        }
      }
    }
  })
})
// 
router.get('/iptDistributeTower', async (ctx, next) => {
  let where = {
    tower: {
      $in: ctx.query.tower.split(',')
    }
  }
  let page = Number(ctx.query.pagenum)//当前第几页
  let size = 10
  let options = { "limit": size, "skip": (page - 1) * size }
  // 某栋宿舍楼所有的宿舍长名单
  const result1 = await dormInfoModel.find(where, null, options).sort({ "tower": 1, "dorm": 1 })
  // 某栋宿舍楼的7间宿舍
  const result2 = await StudentModel.find(where, null).sort({ "tower": 1, "dorm": 1 })
  // 某栋宿舍楼的某宿舍所有人  .sort({ "dorm": 1 })
  const result3 = await StudentModel.find(where).sort({ "tower": 1, "dorm": 1 })
  let count = await dormInfoModel.find(where, null)
  let total = count.length
  // 计算宿舍可用床位后的学生某宿舍数组
  let result = []
  if (result2.length !== 0) {
    result1.forEach(valid => {
      let query = {
        dorm: valid.dorm
      }
      let need = result3.filter(valid => {
        return valid.dorm === query.dorm
      })
      valid.spare = Number(valid.spare) - need.length
      result.push(valid)
    })
    ctx.body = {
      result,
      total,
      meta: {
        msg: "请求数据成功",
        code: 200
      }
    }
  } else {
    ctx.body = {
      meta: {
        msg: "这栋宿舍楼还没有入住的人呦~",
        code: 204 // 表示已经接受到请求，但是没有内容
      }
    }
  }
})
export default router